package org.dromara.system.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.dromara.system.domain.AccessToken;
import org.dromara.system.domain.dto.TemplateMessage;
import org.dromara.system.domain.dto.WeChatTemplateMsg;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;


public  class GzhPushUtil {

    // 必须替换
    public static  String APPID = "wx3152fa8e4bd5c9e5";
    // 必须替换
    public static String SECRET ="3816e3662a2c456a1c2cd225537c47eb";

    private static AccessToken at;






    /**
     *
     * 发送消息
     *
     * @Description 发送模板消息
     * @date 2023年5月30日上午10:57:45
     * @throws IOException
     */
    public static void  doSendMessage () throws IOException {
        String token = getToken();
        // 获取 openid 数组
        List<String> userOpenids = WXPublicAccountHttpUtil.getOpenidList(token);
        // 主要的业务逻辑：
        for (String openId : userOpenids) {
            TemplateMessage templateMessage = new TemplateMessage();
            templateMessage.setTouser(openId);
            templateMessage.setTemplate_id("s94RREhOX_b-ZISWkImovA4qV2DeUHR5LkPSVKb7z2k");
            templateMessage.setTopcolor("#FF0000");
            // key对应创建模板内容中的形参
            //{{title.DATA}} {{username.DATA}} {{quote.DATA}} {{date.DATA}}
            // WeChatTemplateMsg对应实参和字体颜色
            Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
            data.put("title", new WeChatTemplateMsg("你有一条新的消息", "#173177"));
            data.put("username", new WeChatTemplateMsg("黄先生", "#173177"));
            data.put("date", new WeChatTemplateMsg("2023年05月29日 16时24分", "#173177"));
            data.put("quote", new WeChatTemplateMsg("你好", "#173177"));


            templateMessage.setData(data);

//                System.out.println(templateMessage);

            WXPublicAccountHttpUtil.sendMessage(getToken(), templateMessage);

        }

    }
    /**
     *
     * @Description 获取token, 本地缓存有就直接返回，没有就发送请求获取（wx官方api获取token每天有限制，因此需做缓存)
     * @date 2023年5月29日下午4:13:17
     * @return
     */
    public static String getToken () {
        if (at == null || at.isExpired()) {
            getAccessToken();
        }
        return at.getAccessToken();
    }
    /**
     * 给AccessToken赋值
     */
    private static void getAccessToken () {
        // 发送请求获取token
        String token = null;
        try {

            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + APPID + "&secret=" + SECRET;
            token = WXPublicAccountHttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONUtil.parseObj(token);
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        // 创建token对象，并存储
        at = new AccessToken(accessToken, String.valueOf(expiresIn));
        System.out.println(token);
    }
    /**
     * 小程序、公众号在微信开放平台唯一id
     * 获取unionid
     */
    public static String getUnionID (String accessToken,String openid) {
        // 发送请求获取token
        String wxUserString = null;
        try {

            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openid;
            wxUserString = HttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONUtil.parseObj(wxUserString);
        String unionid = (String) jsonObject.get("unionid");
        return unionid;
    }

    /**
     * 获取用户信息
     * @param accessToken
     * @param openid
     * @return
     */
    public static JSONObject getUserString(String accessToken,String openid){
        String buffer = "https://api.weixin.qq.com/cgi-bin/user/info?" +
            "access_token=" + accessToken +
            "&openid=" + openid + "&lang=zh_CN";
        String wxUserString = HttpUtil.get(buffer);
        log.info("获取用户信息===>{}", wxUserString);
        JSONObject jsonObject = JSONUtil.parseObj(wxUserString);
        return jsonObject;
    }
}
